package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("/login")
    //因为前端传过来的数据是Json格式的，所以这里要用@RequestBody接收
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        //1、密码进行MD5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据username查询数据库（数据库该字段设置为唯一了）
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3、没有查到则返回登录失败
        if(emp ==null){
            return R.error("登录失败，没有该账号");
        }
        //4、密码比对
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败，密码错误");
        }

        //5、员工是否被禁用
        if(emp.getStatus() ==0){
            return R.error("员工被禁用");
        }
        //6、登录成功，将员工id存入Session并返回结果
        request.getSession().setAttribute("employee",emp.getId());

        return R.success(emp);
    }


    //员工退出
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    //新增员工（不需要在注解中加value值了，因为他只要类上面的哪个路径就能访问）
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){

        //密码md5加密、另外status默认为1不禁用的，不需要设置
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//直接放进公共里面        employee.setCreateTime(LocalDateTime.now()); //获取系统时间
//        employee.setUpdateTime(LocalDateTime.now()); //获取更新时间

        //获得的是Objcet类型，需要转成Long类型

//        Long empId= (Long) request.getSession().getAttribute("employee");

//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return  R.success("新增员工成功");
    }

    //分页查询(这里的泛型要用Page，不然axios接收的参数对不上，而Page里面有对应的参数)
    //这里的name参数用于模糊查询用的
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //构造分页构造器(第几页、一页显示几条)
        Page<Employee> pageInfo = new Page<>(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();

        //添加过滤条件name为null就不需要查询了
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //不需要返回，因为在page内部，他会自己把我们的数据进行封装(pageInfo自己已经收到了对应的数据)
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    //根据iD修改员工信息(状态)(同上，不需要在加路径)
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
/*        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());*/


        employeeService.updateById(employee); //这个修改只是修改employee对象里面的值不为为null的不会修改
        return R.success("员工信息修改成功");
    }


    //修改员工信息

    //1、获取数据
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if(employee !=null){

            return R.success(employee);
        }
        return R.error("没有查询到对应员工");
    }

}
